<?php

namespace app\admin\controller;

use app\common\model\Classes;
use app\common\model\ClassesStu;
use app\common\model\StudentHabit;
use app\common\model\StudentLog;
use app\common\model\UserStudent;
use app\common\model\User;
use app\service\MsgService;
use app\service\StudentService;
use app\service\WechatService;

class Student extends Base
{

    public $studentLogModel;
    public $studentHabitModel;

    public function __construct()
    {
        parent::__construct();
        $this->studentLogModel = new StudentLog();
        $this->studentHabitModel = new StudentHabit();
    }

    /**
     * 列表
     * @return \think\response\Json
     */
    public function student_list()
    {
        if (request()->isPost()) {
            $data = input('');
            $page = input('page', 1);
            $size = input('size', 20);
            $where = [];
            if ($data['name']) {
                $where['name'] = ['like', "%{$data['name']}%"];
            }
            if ($data['id']) {
                $where['id'] = $data['id'];
            }
            $list = StudentService::S()->queryPage($where, $page, $size);
            $total = StudentService::S()->queryCount($where);
            if ($list) {
                foreach ($list as $key => $value) {
                    $list[$key]['cid'] = array_merge(ClassesStu::getColumn(['sid' => $value['id']], 'cid'), []);
                }
            }
            return returnJson(200, '', compact('page', 'size', 'list', 'total'));
        }
    }

    /**
     * 编辑添加
     * @return \think\response\Json
     */
    public function student_edit()
    {
        if (request()->isPost()) {
            $data = input('');
            if (!$data['name']) {
                return returnJson(202, '请填写姓名');
            }
            if (!$data['pay_time']) {
                return returnJson(202, '请填写缴费日期');
            }
            if (!$data['pay_money']) {
                return returnJson(202, '请填写缴费金额');
            }
            $save_data = [
                'name' => $data['name'],
                'sex' => $data['sex'],
                'birth' => $data['birth'],
                'qiufu_name' => $data['qiufu_name'],
                'update_time' => time(),
                'qiufu_number' => $data['qiufu_number'],
                'warranty' => $data['warranty'],
                'phone' => $data['phone'],
                'jinji' => $data['jinji'],
                'idcard' => $data['idcard'],
                'images' => json_encode($data['images']),
                'month' => $data['month'] ? $data['month'] : 6,
                'send_month' => $data['send_month'] ? $data['send_month'] : 0,
                'pay_time' => strtotime($data['pay_time']),
                'lose_time' => strtotime('+' . $data['month'] + $data['send_month'] . 'month', strtotime($data['pay_time'])),
                'pay_money' => $data['pay_money'],
                'update_time' => time(),
                'tuijian' => $data['tuijian'] ? $data['tuijian'] : '',
                'join_time' => $data['join_time'],
            ];


            if ($data['id']) {
                $where = [
                    'id' => $data['id']
                ];
                $student = \app\common\model\Student::getOne($where);
                $bind = UserStudent::getAll(['sid' => $data['id']]);
                $sign = false;
                foreach ($student as $key => $value) {
                    if (!$sign && in_array($key, ['month', 'send_month', 'pay_time', 'lose_time', 'pay_money', 'tuijian', 'join_time']) && ($value != $save_data[$key])) {
                        if ($bind) {
                            foreach ($bind as $val) {
                                $user_info = \app\common\model\User::getOne(['id' => $val['uid']]);
                                if ($user_info) {
                                    //发消息 TODO
                                    WechatService::S([
                                        'mall_id' => $user_info['mall_id']
                                    ])->send(
                                        1,
                                        User::uid2openid($user_info['id']),
                                        "【缴费记录】缴费记录发生变化，<a href='http://xy.xiyuezuqiu.cn/m/xiyue/pages/money/index?sid=" . $data['id'] . "'>点此查看</a>"
                                    );
                                }
                            }
                        }
                    }
                }
                $bind_sign = false;
                //成长记录
                $this->studentLogModel->where('sid', $data['id'])->delete();
                if ($data['list_log']) {
                    foreach ($data['list_log'] as $key => $val) {
                        foreach ($val as $log_key => $value) {
                            if ($value === '') {
                                $data['list_log'][$key][$log_key] = null;
                            }
                        }
                        $data['list_log'][$key]['update_time'] = time();
                        $data['list_log'][$key]['create_time'] = time();
                        $data['list_log'][$key]['sid'] = $data['id'];
                        unset($data['list_log'][$key]['id']);
                    }
                    $this->studentLogModel->insertAll($data['list_log']);
                    $bind_sign = true;
                }
                //饮食习惯
                $this->studentHabitModel->where('sid', $data['id'])->delete();
                for ($i = 1; $i < 6; $i++) {
                    if ($data['list_' . $i]) {
                        foreach ($data['list_' . $i] as $key => $val) {
                            $val['create_time'] = time();
                            $val['update_time'] = time();
                            $val['sid'] = $data['id'];
                            unset($val['id']);
                            $data['list_' . $i][$key] = $val;
                        }
                        if ($data['list_' . $i]) {
                            $this->studentHabitModel->insertAll($data['list_' . $i]);
                            $bind_sign = true;
                        }
                    }
                }
                if ($bind && $bind_sign && $data['type'] == 2) {
                    foreach ($bind as $value) {
                        $user_info = \app\common\model\User::getOne(['id' => $value['uid']]);
                        if ($user_info) {
                            //发消息 TODO
                            WechatService::S([
                                'mall_id' => $user_info['mall_id']
                            ])->send(
                                1,
                                User::uid2openid($user_info['id']),
                                "【成长档案】档案发生变化，<a href='http://xy.xiyuezuqiu.cn/m/xiyue/pages/student/index?sid=" . $data['id'] . "'>点此查看</a>"
                            );
                        }
                    }
                }
                $res = StudentService::S()->querySave($save_data, $where);
                $res = $data['id'];
            } else {
                $save_data['create_time'] = time();
                $res = StudentService::S()->querySave($save_data);
            }
            if ($res) {
                ClassesStu::setDel(['sid' => $res]);
                $cids = $data['cid'];
                if ($cids) {
                    foreach ($cids as $cid) {
                        $s_data[] = [
                            'sid' => $res,
                            'cid' => $cid,
                            'create_time' => time(),
                            'update_time' => time()
                        ];
                    }
                    ClassesStu::setSaveAll($s_data);
                }
                return returnJson(200, '编辑成功');
            } else {
                return returnJson(202, '编辑失败');
            }
        }
    }

    /**
     * @return \think\response\Json
     */
    public function del_student()
    {
        $input = input();
        if (!$input['id']) {
            return returnJson(1, 'error');
        }
        \app\common\model\student::destroy(['id' => $input['id']]);
        return returnJson(0, '删除成功');
    }

    /**
     * 班级列表
     * @return \think\response\Json
     */
    public function classes_list()
    {
        $data = input('');
        $page = input('page', 1);
        $size = input('size', 20);
        $where = [];
        if ($data['name']) {
            $where['name'] = [
                'like', "%{$data['name']}%"
            ];
        }
        $list = Classes::getPage($where, $page, $size);
        $total = Classes::getCount($where);
        if ($list) {
            foreach ($list as $key => $value) {
                $list[$key]['sid'] = array_merge(ClassesStu::getColumn(['cid' => $value['id']], 'sid'), []);
                if ($list[$key]['sid']) {
                    $list[$key]['s_lst'] = \app\common\model\Student::getPage(['id' => ['in', $list[$key]['sid']]]);
                } else {
                    $list[$key]['s_lst'] = [];
                }
            }
        } else {
            $list = [];
        }
        return returnJson(200, '', compact('list', 'total', 'page', 'size'));
    }

    /**
     * 全部学员
     * @return \think\response\Json
     */
    public function all_student_list()
    {
        $list = \app\common\model\Student::getAll([], '', 'id,name');
        if (!$list) {
            $list = [];
        }
        return returnJson(200, '', $list);
    }

    /**
     * 全部班级
     * @return \think\response\Json
     */
    public function all_classes_list()
    {
        $list = \app\common\model\Classes::getAll([], '', 'id,name');
        if (!$list) {
            $list = [];
        }
        return returnJson(200, '', $list);
    }

    /**
     * 编辑班级
     * @return \think\response\Json
     */
    public function classes_edit()
    {
        $data = input('');
        if (!$data['name']) {
            return returnJson(202, '请填写班级名称');
        }
        $save_data = [
            'name' => $data['name'],
            'update_time' => time()
        ];
        if ($data['id']) {
            $res = Classes::update($save_data, ['id' => $data['id']]);
            if ($res) {
                if ($data['sid']) {
                    ClassesStu::setDel(['cid' => $data['id']]);
                    foreach ($data['sid'] as $val) {
                        $stu_data[] = [
                            'sid' => $val,
                            'cid' => $data['id'],
                            'update_time' => time(),
                            'create_time' => time()
                        ];
                    }
                    ClassesStu::setSaveAll($stu_data);
                }
                return returnJson(200, '编辑成功');
            } else {
                return returnJson(202, '编辑失败');
            }
        } else {
            $save_data['create_time'] = time();
            $res = Classes::setInsertGetId($save_data);
            if ($res) {
                foreach ($data['sid'] as $val) {
                    $stu_data[] = [
                        'sid' => $val,
                        'cid' => $res,
                        'update_time' => time(),
                        'create_time' => time()
                    ];
                }
                if ($stu_data)
                    ClassesStu::setSaveAll($stu_data);
                return returnJson(200, '添加成功');
            } else {
                return returnJson(202, '添加失败');
            }
        }
    }

    /**
     * 全部班级学员
     * @return \think\response\Json
     */
    public function all_classes_stu_list()
    {
        $list = Classes::getAll([], '', 'id,name');
        if ($list) {
            foreach ($list as $key => $value) {
                $sids = ClassesStu::getColumn(['cid' => $value['id']], 'sid');
                $list[$key]['s_lst'] = \app\common\model\Student::getAll(['id' => ['in', $sids]], '', 'id,name');
            }
        }
        return returnJson(200, '', $list);
    }

}

